package com.example.yichuangyun.mvvm.ui.activity.order;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityOrderAddFollowBinding;
import com.example.yichuangyun.dialog.TreeDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.order.AttachmentModel;
import com.example.yichuangyun.model.order.FileTypeModel;
import com.example.yichuangyun.model.order.OrderAddFollowParamsModel;
import com.example.yichuangyun.model.order.RealNameModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.order.view.OrderAddFollowViewModel;
import com.example.yichuangyun.mvvm.ui.adapter.GridImageAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DensityUtil;
import com.example.yichuangyun.utils.FileUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;
import com.example.yichuangyun.utils.pictrue.GlideEngine;
import com.example.yichuangyun.utils.producttreelist.ProductNodeModel;
import com.example.yichuangyun.utils.treelist.Node;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.style.PictureSelectorStyle;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 订单跟进
 */
@SuppressLint("NotifyDataSetChanged")
public class OrderAddFollowActivity extends BaseActivity<ActivityOrderAddFollowBinding, OrderAddFollowViewModel> {

    private String orderId;
    private String orderNo;
    private final List<String> options1Items = new ArrayList<>();
    private final List<List<String>> options2Items = new ArrayList<>();
    private OptionsPickerView<String> mOptionsPicker;
    private List<FileTypeModel> fileTypeData = new ArrayList<>();
    private String fileTypeId;
    private GridImageAdapter mAdapter;
    private ActivityResultLauncher<Intent> launcherResult;
    private final List<LocalMedia> mSelectList = new ArrayList<>();
    private final OrderAddFollowParamsModel addFollowParamsModel = new OrderAddFollowParamsModel();
    private final List<OrderAddFollowParamsModel.AttachmentListModel> attachmentList = new ArrayList<>();
    private TreeDialog treeDialog;
    private final List<Node> mTreeData = new ArrayList<>();
    private List<Node> chooseReminderData = new ArrayList<>();
    private String mKeyword = "";

    @Override
    protected OrderAddFollowViewModel bindModel() {
        return getViewModel(this, OrderAddFollowViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        initTitleBar(getString(R.string.add_follow));
        binding.setOrderAddFollowViewModel(viewModel);
        launcherResult = createActivityResultLauncher();
        binding.recyclerView.setLayoutManager(new GridLayoutManager(context, 4));
        binding.recyclerView.addItemDecoration(new GridSpacingItemDecoration(4,
                DensityUtil.dip2px(this, 8), false));
        mAdapter = new GridImageAdapter(context, onAddPicClickListener);
        binding.recyclerView.setAdapter(mAdapter);
        viewModel.getFileType();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            orderId = bundle.getString(Constant.orderIdKey);
            orderNo = bundle.getString(Constant.orderNoKey);
        }
        initTreeDialog();
        viewModel.getTreeList("");
    }

    @Override
    protected void initClick() {
        binding.etInfo.setOnTextChangeListener(text -> {
            binding.tvTextCount.setText(getString(R.string.text_count, text.toString().trim().length()));
            changeBtnStatus();
        });
        // 附件类型返回数据
        viewModel.fileTypeMutableLiveData.observe(this, fileTypeModels -> {
            fileTypeData = fileTypeModels;
            for (FileTypeModel fileTypeModel : fileTypeModels) {
                options1Items.add(fileTypeModel.getName());
                List<String> strings = new ArrayList<>();
                for (FileTypeModel.FileTypeChildren children : fileTypeModel.getChildren()) {
                    strings.add(children.getName());
                }
                options2Items.add(strings);
            }
            initPickerView();
        });

        // 附件类型点击事件
        viewModel.onDelayClick(binding.rlFileType, o -> {
            CommonUtil.closeKeyboard(OrderAddFollowActivity.this);
            if (mOptionsPicker != null) {
                mOptionsPicker.show();
            }
        });

        // 图片点击事件
        mAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                CommonUtil.closeKeyboard(OrderAddFollowActivity.this);
                ArrayList<LocalMedia> selectList = (ArrayList<LocalMedia>) mAdapter.getData();
                if (selectList.size() > 0) {
                    PictureSelector.create(OrderAddFollowActivity.this)
                            .openPreview()
                            .setImageEngine(GlideEngine.createGlideEngine())
                            .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                                @Override
                                public void onPreviewDelete(int position) {
                                    mAdapter.remove(position);
                                    mAdapter.notifyItemRemoved(position);
                                }

                                @Override
                                public boolean onLongPressDownload(Context context, LocalMedia media) {  // 长按保存图片
                                    return true;
                                }
                            })
                            .startActivityPreview(position, true, selectList);
                }

            }

            @Override
            public void openPicture() {

            }
        });

        mAdapter.setOnDeleteClickListener((list, position) -> {
            if (attachmentList.size() > 0) {
                String path = attachmentList.get(position).getAttachmentList().get(0).getAttachmentPath();
                IntStream.range(0, attachmentList.size()).filter(i ->
                                attachmentList.get(i).getAttachmentList().get(0).getAttachmentPath().equals(path)).
                        boxed().findFirst().map(i -> attachmentList.remove((int) i));
                Log.e("@@@@@@@@333", new Gson().toJson(attachmentList));
            }
            changeBtnStatus();
        });

        // 图片上传成功
        viewModel.attachmentModelMutableLiveData.observe(this, attachmentModel -> {
            OrderAddFollowParamsModel.AttachmentListModel attachmentListModel = new OrderAddFollowParamsModel.AttachmentListModel();
            List<AttachmentModel> attList = new ArrayList<>();
            attList.add(attachmentModel);
            attachmentListModel.setAttachmentList(attList);
            attachmentList.add(attachmentListModel);
            changeBtnStatus();
        });

        // 保存按钮
        viewModel.onDelayClick(binding.btnConfirm, o -> {
            UMengUtil.setCountEventId(Constant.ADD_ORDER_FOLLOW);
            addFollowParamsModel.setOrderId(orderId);
            addFollowParamsModel.setOrderNo(orderNo);
            addFollowParamsModel.setDetail(viewModel.content.getValue().trim());
            addFollowParamsModel.setAttachment(attachmentList);
            if (chooseReminderData.size() > 0) {
                List<RealNameModel> reminderData = new ArrayList<>();
                for (Node node : chooseReminderData) {
                    reminderData.add(new RealNameModel(node.getName(), viewModel.content.getValue().trim(), node.getJobNumber(), node.getOrgId()));
                }
                addFollowParamsModel.setStaffList(reminderData);
            }
            Log.e("@@@@@@@@@", new Gson().toJson(addFollowParamsModel));
            viewModel.addOrderFollow(addFollowParamsModel);
        });

        // 订单跟进成功
        viewModel.mAddSuccessData.observe(this, s -> {
            EventBus.getDefault().post(new EventBusModel(Constant.refreshOrderFollowList));
            OrderAddFollowActivity.this.finish();
        });

        viewModel.treeData.observe(this, setShareBean -> {
            dismissLoadingDialog();
            if (setShareBean.getData() != null) {
                Node node = setShareBean.getData();
                mTreeData.add(new Node(node.getName(), node.getId(), node.getParentId(),
                        node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
                initList(node.getChildren());
                initList(node.getUserList());
                if (chooseReminderData.size() > 0) {
                    for (Node m : mTreeData) {
                        for (Node n : chooseReminderData) {
                            if (m.getId().equals(n.getId())) {
                                m.setChecked(true);
                            }
                        }
                    }
                }
            }
            treeDialog.refreshData(TextUtils.isEmpty(mKeyword) ? 1 : 10);
        });

        viewModel.onDelayClick(binding.rlMessageReminder, o -> {
            treeDialog.setFlag(2);
            treeDialog.setTitle(getString(R.string.please_choose_reminder));
            treeDialog.showDialog();
        });
    }

    private final GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            if (TextUtils.isEmpty(binding.tvFileType.getText().toString())) {
                ToastHelper.show(context.getString(R.string.choose_file_type_hint));
            } else {
                PictureSelector.create(context).openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .setImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                        .setSelectorUIStyle(new PictureSelectorStyle())
                        .setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                        .isMaxSelectEnabledMask(true)
                        .setMaxSelectNum(20)
                        .setMinSelectNum(1)
//                    .setSelectedData(mAdapter.getData())
                        .setCompressEngine((CompressFileEngine) (context, source, call) -> Luban.with(context).load(source).ignoreBy(100)
                                .setCompressListener(new OnNewCompressListener() {
                                    @Override
                                    public void onStart() {
                                    }

                                    @Override
                                    public void onSuccess(String source, File compressFile) {
                                        if (call != null) {
                                            call.onCallback(source, compressFile.getAbsolutePath());
                                        }
                                    }

                                    @Override
                                    public void onError(String source, Throwable e) {
                                        if (call != null) {
                                            call.onCallback(source, null);
                                        }
                                    }
                                }).launch())
                        .forResult(launcherResult);
            }
        }
    };

    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    int resultCode = result.getResultCode();
                    if (resultCode == RESULT_OK) {
                        List<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                        for (int i = 0; i < selectList.size(); i++) {
                            LocalMedia media = selectList.get(i);
                            File file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                            File file2 = new File(media.getRealPath());
                            try {
                                Log.e("@@@@@@@@@", "压缩前===" + FileUtil.getFileSize(file2) + "-----压缩后===" + FileUtil.getFileSize(file));
                                Log.e("@@@@@@@@@", "---------------------------");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            viewModel.uploadImages(file, fileTypeId, media.getFileName());
                        }
                        mSelectList.addAll(selectList);
                        mAdapter.setList(mSelectList);
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void initPickerView() {
        mOptionsPicker = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            if (fileTypeData != null && fileTypeData.size() > 0) {
                binding.tvFileType.setText(fileTypeData.get(options1).getChildren().get(options2).getName());
                fileTypeId = fileTypeData.get(options1).getChildren().get(options2).getId();
            }
            changeBtnStatus();
            mOptionsPicker.dismiss();
        })
                .setContentTextSize(20)
                .setLayoutRes(R.layout.pickerview_custom_options, v -> {
                    //自定义布局中的控件初始化及事件处理
                    final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                    final TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                    tvSubmit.setOnClickListener(v1 -> mOptionsPicker.returnData());
                    tv_cancel.setOnClickListener(v12 -> mOptionsPicker.dismiss());
                })
                .build();
        mOptionsPicker.setPicker(options1Items);
        mOptionsPicker.setPicker(options1Items, options2Items);
    }

    private void changeBtnStatus() {
        if (viewModel.content.getValue() != null) {
            if (!TextUtils.isEmpty(viewModel.content.getValue().trim())) {
                binding.btnConfirm.setEnabled(true);
                binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
            } else {
                binding.btnConfirm.setEnabled(false);
                binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
            }
        }
    }

    private void initTreeDialog() {
        treeDialog = new TreeDialog(this, mTreeData, false) {

            @Override
            public void confirm(List<Node> nodes) {
                chooseReminderData = nodes;
                if (nodes.size() > 0) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < nodes.size(); i++) {
                        Node node = nodes.get(i);
                        if (i == 0) {
                            stringBuilder.append(node.getName());
                        }
                        if (i == 1) {
                            if (nodes.size() > 2) {
                                stringBuilder.append("，").append(node.getName()).append("等");
                            } else {
                                stringBuilder.append("，").append(node.getName());
                            }
                        }
                    }
                    binding.tvMessageReminder.setText(stringBuilder.toString());
                } else {
                    binding.tvMessageReminder.setText("");
                }
            }

            @Override
            public void search(String keyword, Node node) {
                showLoadingDialog();
                mKeyword = keyword;
                viewModel.getTreeList(keyword);
            }
        };
    }

    private void initList(List<Node> list) {
        if (list == null || list.size() == 0)
            return;
        for (int i = 0; i < list.size(); i++) {
            Node node = list.get(i);
            if (node.getIsLeave() != 1) {
                mTreeData.add(new Node(node.getName(), node.getId(), node.getParentId(),
                        node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId(), node.getIsLeave()));
            }
            if (node.getChildren() == null || node.getChildren().size() == 0) {
                initList(node.getUserList());
            } else {
                initList(node.getChildren());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (launcherResult != null) {
            launcherResult.unregister();
        }
    }
}